#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'walkingsky tangxn_1@163.com'

import requests
import json
from models.runjs import decode 
from models.config import Config

class HuobanApi:

    def __init__(self):
        '''
            初始化参数：username： string  用户名
                        password：string 密码
                        space_id：string 工作区id
                        dev： bool 是否为dev环境测试
        '''
        env = Config().get_test_env()
        #self.space_id = space_id
        self.space_id = '4000000003068432'
        if ( env == 'dev' ):
            self.is_dev = True
            self.token_url = 'http://token.dev.huoban.com/token'
            self.api_url = 'http://api.dev.huoban.com/v2/'
        else:
            self.token_url = 'https://token.huoban.com/token'
            self.api_url = 'https://api.huoban.com/v2/' 
           


    def login(self,username,password):
        '''
        登录伙伴
        '''
        self.username = username
        self.password = password
        params_str = '{"username":"'+ self.username +'","password":"'+ self.password +'","client_id":1,"grant_type":"password"}'
        params_str ={'username':self.username,'password':self.password,'client_id':1,'grant_type':'password'}
        #print(params_str)
        res = requests.post(self.token_url,json = params_str )
        #print(res.text)
        res_json = res.json()
        if (  'code' in res_json.keys() ):
            #登录失败
            print(res_json.get('message'))
            return False
        else:
            access_token = res_json.get('access_token')
            #print(access_token)
            self.token = decode(access_token)
            #self.set_headers()
            return self.token
    
    def set_headers(self,space_id):
        self.space_id = space_id
        self.headers={"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
                "Accept" : "application/json",
                "Accept-Language" : "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                "Connection" : "keep-alive",
                "Authorization" : "Bearer " + self.token,
                "Content-Type": "application/json",
                "X-Huoban-Return-Alias-Space-Id":self.space_id}

    
    def write_data(self,table_name,data_json):
        '''
        
        '''
        url = self.api_url +'item/table/T::'+table_name

        json_params = {"fields":json.loads(data_json)}
        #print(json_params)
        #json_params = {"fields":{"2200000140161378":name ,"2200000140161379":code,"2200000140161339":date,"2200000140161340":price}}
        headers = self.headers
        res = requests.post(url , json = json_params,headers=headers )
        res_json = res.json()
        if (  'code' in res_json.keys() ):
            #获取数据失败
            print(res_json.get('message'))
            return False
        else:
            return True

    def write_datas(self,table_name,datas_json):
        json_datas = json.loads(datas_json)
        num = 0 
        i = 0
        for json_data in json_datas:
            
            data = json.dumps(json_data)
            result = self.write_data(table_name,data)
            if result :
                num = num + 1
            i = i + 1

        return [i,num]

    def modify_datas(self,table_name,data_json):
        
        url = self.api_url +'item/table/T::'+table_name + '/update'

        json_params = json.loads(data_json)
        #print(json_params)
        #json_params = {"fields":{"2200000140161378":name ,"2200000140161379":code,"2200000140161339":date,"2200000140161340":price}}
        headers = self.headers
        res = requests.post(url , json = json_params,headers=headers )
        if res.status_code != 200:
            return False
        else:
            return True

    def find_datas(self,table_name,data_json):
        
        url = self.api_url +'item/table/T::'+table_name + '/find'

        json_params = json.loads(data_json)
        #print(json_params)
        #json_params = {"fields":{"2200000140161378":name ,"2200000140161379":code,"2200000140161339":date,"2200000140161340":price}}
        headers = self.headers
        res = requests.post(url , json = json_params,headers=headers )
        if res.status_code != 200:
            return False
        else:
            res_json = res.json()
            total = res_json.get('total')
            filtered = res_json.get('filtered')
            return [total,filtered]

    def delete_datas(self,table_name,data_json):
        
        url = self.api_url +'item/table/T::'+table_name + '/delete'

        json_params = json.loads(data_json)
    
        headers = self.headers
        res = requests.post(url , json = json_params,headers=headers )
        if res.status_code != 200:
            return False
        else:
            return True


    
            
       
  